package com.rainkaze.lifeharbor.tools.yiyan;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.ActivityToolYiyanBinding;
import com.rainkaze.lifeharbor.tools.yiyan.model.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.Data;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class YiYanActivity extends AppCompatActivity {

    private static final String TAG = "YiYanActivity";
    private static final String API_TOKEN = "LwExDtUWhF3rH5ib";
    private static final String API_BASE_URL = "https://v2.alapi.cn/api/hitokoto";

    // 声明 Binding 对象
    private ActivityToolYiyanBinding binding;

    private OkHttpClient okHttpClient;
    private Map<String, String> yiYanTypes;
    private String currentSelectedTypeCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使用 View Binding 初始化视图
        binding = ActivityToolYiyanBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化 OkHttpClient
        okHttpClient = new OkHttpClient();

        // Toolbar 设置
        setSupportActionBar(binding.toolbarYiyan);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        setupYiYanTypes();
        setupSpinner();

        binding.buttonRefreshYiyan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchYiYan();
            }
        });
    }

    private void setupYiYanTypes() {
        yiYanTypes = new LinkedHashMap<>();
        yiYanTypes.put("任意类型", "");
        yiYanTypes.put("动画", "a");
        yiYanTypes.put("漫画", "b");
        yiYanTypes.put("游戏", "c");
        yiYanTypes.put("小说", "d");
        yiYanTypes.put("原创", "e");
        yiYanTypes.put("来自网络", "f");
        yiYanTypes.put("其他", "g");
    }

    private void setupSpinner() {
        List<String> typeNames = new ArrayList<>(yiYanTypes.keySet());
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, typeNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinnerYiyanType.setAdapter(adapter);

        binding.spinnerYiyanType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedTypeName = parent.getItemAtPosition(position).toString();
                currentSelectedTypeCode = yiYanTypes.get(selectedTypeName);
                fetchYiYan();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        if (!typeNames.isEmpty()) {
            binding.spinnerYiyanType.setSelection(0);
            currentSelectedTypeCode = yiYanTypes.get(typeNames.get(0));
        }
    }


    private void fetchYiYan() {
        binding.progressBarYiyan.setVisibility(View.VISIBLE);
        binding.textViewHitokoto.setText("正在加载一言...");
        binding.textViewFrom.setText("");
        binding.textViewCreator.setText("");
        binding.textViewCreator.setVisibility(View.GONE);



        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_BASE_URL).newBuilder();
        urlBuilder.addQueryParameter("token", API_TOKEN);
        if (currentSelectedTypeCode != null && !currentSelectedTypeCode.isEmpty()) {
            urlBuilder.addQueryParameter("type", currentSelectedTypeCode);
        }
        String apiUrl = urlBuilder.build().toString();

        Log.d(TAG, "每日一言请求URL: " + apiUrl);

        Request request = new Request.Builder()
                .url(apiUrl)
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "请求失败 ", e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.progressBarYiyan.setVisibility(View.GONE);
                        binding.textViewHitokoto.setText("网络请求失败");
                        Toast.makeText(YiYanActivity.this, "网络错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        throw new IOException("返回结果为空");
                    }
                    responseBodyString = responseBody.string();
                }

                if (!response.isSuccessful()) {
                    Log.e(TAG, "API请求错误: " + response.message() + ", code: " + response.code() + ", body: " + responseBodyString);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.progressBarYiyan.setVisibility(View.GONE);
                            binding.textViewHitokoto.setText("获取失败: " + response.code() + " " + response.message());
                            Toast.makeText(YiYanActivity.this, "获取一言失败: " + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }

                Log.d(TAG, "每日一言请求返回结果: " + responseBodyString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.progressBarYiyan.setVisibility(View.GONE);
                        try {
                            Gson gson = new Gson();
                            YiYanResponse yiYanResponse = gson.fromJson(responseBodyString, YiYanResponse.class);

                            if (yiYanResponse != null && yiYanResponse.getCode() == 200 && yiYanResponse.getData() != null) {
                                YiYanData data = yiYanResponse.getData();
                                binding.textViewHitokoto.setText(data.getHitokoto());
                                String fromText = "—— " + (data.getFrom() != null ? data.getFrom() : "未知来源");
                                if (data.getFrom_who() != null && !data.getFrom_who().isEmpty()) {
                                    fromText += " (" + data.getFrom_who() + ")";
                                }
                                binding.textViewFrom.setText(fromText);

                                if (data.getCreator() != null && !data.getCreator().isEmpty()) {
                                    binding.textViewCreator.setText("创作者: " + data.getCreator());
                                    binding.textViewCreator.setVisibility(View.VISIBLE);
                                } else {
                                    binding.textViewCreator.setVisibility(View.GONE);
                                }
                            } else {
                                String errorMsg = "获取失败";
                                if (yiYanResponse != null && yiYanResponse.getMsg() != null) {
                                    errorMsg += ": " + yiYanResponse.getMsg();
                                } else if (yiYanResponse != null) {
                                    if(yiYanResponse.getCode() == 429) {
                                        errorMsg += "请求次数过多，请稍后再试";
                                    }else{
                                        errorMsg += "未知错误，错误代码"+yiYanResponse.getCode();
                                    }
                                }
                                binding.textViewHitokoto.setText(errorMsg);
                                Log.e(TAG, "API错误或违法数据: " + errorMsg);
                                Toast.makeText(YiYanActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "JSON格式错误: ", e);
                            binding.textViewHitokoto.setText("解析数据失败");
                            Toast.makeText(YiYanActivity.this, "数据处理错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}